package com.cskaoyan.wordmemorize.controller.admin;

import com.cskaoyan.wordmemorize.auth.SaAdminCheckPermission;
import com.cskaoyan.wordmemorize.auth.StpKit;
import com.cskaoyan.wordmemorize.common.result.Result;
import com.cskaoyan.wordmemorize.dto.admin.ExcelAddOperateDTO;
import com.cskaoyan.wordmemorize.service.VocService;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping("/admin/voc")
public class AdminExcelController {

    @Autowired
    VocService vocService;

    // 上传Excel文件并解析(校验)
    @SaAdminCheckPermission("admin:voc:excel:upload")
    @PostMapping("excel/validate")
    public Result vocExcelVerify(@RequestParam("vocExcel") MultipartFile file) throws IOException {
        // 在该service方法中完成Excel文件内容的读取
        vocService.vocExcelValidate(file);
        return Result.ok();
    }

    // 上传Excel文件并存储到数据库
    @SaAdminCheckPermission("admin:voc:excel:upload")
    @PostMapping("excel")
    public Result< ExcelAddOperateDTO> addVocExcel(@RequestParam("vocExcel") MultipartFile file) throws IOException {
        // 获取当前登录的后台用户id
        Long employeeId = StpKit.ADMIN.getLoginIdAsLong();
        // 调用该方法完成Excel上传单词功能
        ExcelAddOperateDTO excelAddOperateDTO = vocService.addVocExcel(file, employeeId);
        return Result.ok(excelAddOperateDTO);
    }

    // 下载Excel模板
    @SaAdminCheckPermission("admin:voc:excel:upload")
    @GetMapping("template")
    public ResponseEntity<byte[]> downloadTemplate() throws IOException {

        // 使用ClassPathResource读取资源文件
        ClassPathResource resource;
        resource = new ClassPathResource("templates/单词上传模版.xlsx");

        // 检查文件是否存在
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        // 读取文件内容
        InputStream inputStream = resource.getInputStream();
        byte[] fileBytes = IOUtils.toByteArray(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment",
                URLEncoder.encode(resource.getFilename(), "UTF-8"));

        return ResponseEntity.ok()
                .headers(headers)
                .body(fileBytes);
    }
}
